let fs = require('graceful-fs'),
    iconv = require('iconv-lite');

let child_process = require("child_process");
let num = 0,
    timer;

$(function () {
    fs.exists("D:/Landscape_Class_Statistics", function (exists) {
        if (exists) {
            $(".initialize").hide();
        } else {
        }
    })
})

//获取文件路径

$('#file').change(function () {

        let path = $('#file')[0].files;
        for (let f of path) {
            oldpath = f.path;
        }
        pathname = oldpath.replace(/\\/g, "/").split("/").pop();

        if (pathname.indexOf(".tif") != -1) {
            $(".txt1").addClass("border").find("h5").text(pathname);
        }
        if (pathname.indexOf(".tfw") != -1) {
            $(".txt2").addClass("border").find("h5").text(pathname);
        }

        let temporarypath = pathprefix + pathname;
        newpath = temporarypath;
        console.log(newpath);
        console.log(oldpath);
        fs.appendFile(temporarypath, " ", function (err) {
            if (err) {
                pathflag = false;
            } else {
                pathflag = true;
            }
        })
    }
);

//上传文件
function up() {
    if (pathflag == true) {
        function mycopy(path1, path2) {
            fs.readFile(path1, function (err, data) {
                if (err) {
                    console.log(err);
                } else {
                    var data1 = data.toString();
                    fs.writeFile(path2, data1, function (err) {
                        if (err) {
                            alert(err);
                            if (pathname.indexOf(".tif") != -1) {
                                $(".txt1").find("span").val("上传失败").css("color", "red");
                            }
                            if (pathname.indexOf(".tfw") != -1) {
                                $(".txt2").find("span").val("上传失败").css("color", "red");
                            }
                        } else {
                            alert("上传成功");
                            if (pathname.indexOf(".tif") != -1) {
                                $(".txt1").find("span").text("上传成功").css("color", "green");
                            }
                            if (pathname.indexOf(".tfw") != -1) {
                                $(".txt2").find("span").text("上传成功").css("color", "green");
                            }
                        }
                    })
                }
            })
        }

        mycopy(oldpath, newpath)
    } else {
        alert("请选择上传文件")
    }
}

//添加字段
function add() {
    var li = '<li>' +
        '<span>编号:</span><input type="number" class="deal">' +
        '<span>类型:</span><input type="text" class="deal"> ' +
        '<div class="close"></div>' +
        '</li>';

    $(".flist").append(li);
}

//删除字段
$(".flist").on('click', '.close', function () {
    var ind = $(this).index(".close");
    $(".flist li").eq(ind).remove();
})

//生成文件
function create() {
    var v = $(".flist li");
    var array = [],
        str;
    for (var i = 0; i < v.length; i++) {
        var inp = $(v[i]).find("input");
        var arr = [];
        for (var k = 0; k < inp.length; k++) {
            var str = inp.eq(k).val();
            arr.push(str);
        }
        str = arr.join(",");
        array.push(str);
    }
    array.unshift("Code,Class Name")
    var text = array.join("\r\n");
    text = iconv.encode(text, 'gbk');
    mk(csv, text)
}

function createsize() {
    var str = $("#size").val(),
        text = "class,size\r\nraster," + str;
    text = iconv.encode(text, 'gbk');
    mk(csv2, text)
}

//监测


function watch() {
    timer = setInterval(function () {
        fs.exists("D:/Landscape_Class_Statistics/result/result.csv", function (exists) {
            if (exists) {
                $(".load").hide();
                alert("生成成功\r\nD:/Landscape_Class_Statistics/result目录下")
                clearInterval(timer);
            } else {
            }
        })
    }, 1000);
}
//启动
function go() {
    fs.exists("D:/Landscape_Class_Statistics/result/result.csv", function (exists) {
        if (exists) {
            fs.unlink('D:/Landscape_Class_Statistics/result/result.csv', function (err) {
                if (err) {
                    alert("生成失败\r\nD:/Landscape_Class_Statistics/result/result.csv被程序占用")
                } else {
                    $(".load").show();
                    child_process.execFile("landscape_class_statistics.bat", null, {cwd: 'D:/Landscape_Class_Statistics/function'})
                    watch()
                }
            })
        } else {
            $(".load").show();
            child_process.execFile("landscape_class_statistics.bat", null, {cwd: 'D:/Landscape_Class_Statistics/function'})
            watch()
        }
    })


}


//第一次启动
function frist() {
    child_process.execFile("First_run.bat", null, {cwd: 'D:/Landscape_Class_Statistics/First_run'})
}
//初始化
function start() {

    $(".load").show();

    var stat = fs.stat;
    var copy = function (src, dst) {
        // 读取目录中的所有文件/目录
        fs.readdir(src, function (err, paths) {
            if (err) {
                throw err;
            }
            paths.forEach(function (path) {
                var _src = src + '/' + path,
                    _dst = dst + '/' + path,
                    readable, writable;
                stat(_src, function (err, st) {
                    if (err) {
                        throw err;
                    }
                    // 判断是否为文件
                    if (st.isFile()) {
                        // 创建读取流
                        readable = fs.createReadStream(_src);
                        // 创建写入流
                        writable = fs.createWriteStream(_dst);
                        // 通过管道来传输流
                        readable.pipe(writable);
                    }
                    // 如果是目录则递归调用自身
                    else if (st.isDirectory()) {
                        exists(_src, _dst, copy);
                    }
                });
            });
        });
        num++;

        if (num == 934) {
            $(".load").hide();
            $(".initialize").fadeOut("slow");
            frist();
        }
    };
// 在复制目录前要判断该目录是否存在，不存在需要先创建目录
    var exists = function (src, dst, callback) {
        fs.exists(dst, function (exists) {
            // 已存在
            if (exists) {
                callback(src, dst);
            }
            // 不存在
            else {
                fs.mkdir(dst, function () {
                    callback(src, dst);
                });
            }
        });
    };
// 复制目录
    exists('./relyon', 'D:/', copy);
}

function mk(filename, value) {
    fs.writeFile(filename, value,"ascii",function (err) {
        if (err) {
            alert(err);
        } else {
            alert("添加成功")
        }
    });

}
